// Copyright (C) 2024 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.acceptance;

import com.google.gerrit.common.Nullable;
import com.google.gerrit.testing.TestTimeUtil;
import java.sql.Timestamp;
import java.time.Instant;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class TimeSettingsTestRule implements TestRule {
  private final TestConfigRule config;
  private String systemTimeZone;

  public TimeSettingsTestRule(TestConfigRule config) {
    this.config = config;
  }

  @Override
  public Statement apply(Statement statement, Description description) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        beforeTest();
        statement.evaluate();
        afterTest();
      }
    };
  }

  private void beforeTest() {
    setTimeSettings(
        config.classDescription().useSystemTime(),
        config.classDescription().useClockStep(),
        config.classDescription().useTimezone());
    setTimeSettings(
        config.methodDescription().useSystemTime(),
        config.methodDescription().useClockStep(),
        config.methodDescription().useTimezone());
  }

  private void afterTest() {
    resetTimeSettings();
  }

  private void setTimeSettings(
      boolean useSystemTime,
      @Nullable UseClockStep useClockStep,
      @Nullable UseTimezone useTimezone) {
    if (useSystemTime) {
      TestTimeUtil.useSystemTime();
    } else if (useClockStep != null) {
      TestTimeUtil.resetWithClockStep(useClockStep.clockStep(), useClockStep.clockStepUnit());
      if (useClockStep.startAtEpoch()) {
        TestTimeUtil.setClock(Timestamp.from(Instant.EPOCH));
      }
    }
    if (useTimezone != null) {
      systemTimeZone = System.setProperty("user.timezone", useTimezone.timezone());
    }
  }

  private void resetTimeSettings() {
    TestTimeUtil.useSystemTime();
    if (systemTimeZone != null) {
      System.setProperty("user.timezone", systemTimeZone);
      systemTimeZone = null;
    }
  }
}
